package com.face.server.controller;

import com.face.RespMsg;
import com.face.server.repository.CameraRepository;
import com.face.server.entity.Camera;
import com.face.server.service.CSVService;
import com.face.server.service.RaspiService;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

import static java.util.stream.Collectors.toList;
import static org.springframework.data.mongodb.core.query.Criteria.where;

@RestController
@RequestMapping("/raspi")
public class RaspiController {

    @Autowired
    CameraRepository cameraRepository;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    CSVService csvService;

    @Autowired
    RaspiService raspiService;

    @GetMapping
    RespMsg all(@PageableDefault(size = 10000) Pageable pageable) {
        return RespMsg.build(cameraRepository.findBy(pageable));
    }

    @PutMapping
    RespMsg put(MultipartFile file) throws IOException {
        return file == null ?
                RespMsg.error("对不起，文件不能为空") :
                csvService.parseCamera(file);
    }

    @PostMapping
    RespMsg save(@RequestBody @Validated Camera camera) {
        return RespMsg.build(cameraRepository.save(camera).getId());
    }


    @DeleteMapping
    RespMsg save(String[] id) {
        if (id == null) {
            return RespMsg.error("对不起，请选择摄像头");
        }
        cameraRepository.delete(Arrays.stream(id).map(s -> {
            Camera camera = new Camera();
            camera.setId(s);
            return camera;
        }).collect(toList()));
        return RespMsg.build("删除" + id.length + "条记录");
    }

    @GetMapping("build/status")
    RespMsg findByName(int build, boolean closed,
                       @PageableDefault Pageable pageable) {
        return RespMsg.build(
                cameraRepository.findByClosedOrDormitoryBuildNum(closed, build, pageable)
        );
    }

    @PutMapping("id")
    RespMsg open(String[] id) {
        /*其实无视了多个设备*/
        rabbitTemplate.convertAndSend("knob", false);
        return raspiService.update(id, false);
    }


    @DeleteMapping("id")
    RespMsg close(String[] id) {
        /*其实无视了多个设备*/
        rabbitTemplate.convertAndSend("knob", true);
        return raspiService.update(id, true);
    }
}


